package mongodb

import (
	"fmt"
	"gitee.com/dreamwood/ez"
	"os/exec"
)

func createDocumentFile(c *Creator, content []byte) {
	path := fmt.Sprintf(
		"%s/app/%s/documents/%s_.go",
		root, c.Table.Path, c.Table.Name)
	ez.CreateFile(path, content)
	wg.Add(1)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt 5", e.Error())
		}
		wg.Done()
	}()
}
func createCrudFile(c *Creator, content []byte) {
	path := fmt.Sprintf(
		"%s/app/%s/documents/%s_CURD.go",
		root, c.Table.Path, c.Table.Name)
	ez.CreateFile(path, content)
	go func() {
		e := exec.Command("go", "fmt", path).Run()
		if e != nil {
			println("go fmt 5", e.Error())
		}
	}()
}

/***************************Model创建*********************************/
type OrmField struct {
	Name string
	Type string
	Tags string
}

func CreateDocument(creator *Creator) {
	content := twigger.Render("/mongodb/model.twig", creator)
	createDocumentFile(creator, []byte(content))
}
func CreateNestedDocument(creator *Creator) string {
	var content string
	for _, table := range creator.RelationTables {
		content += "\n"
		content += fmt.Sprintf("type %s struct {\n", table.Table.Name)
		for _, field := range table.Fields {

			content += fmt.Sprintf(
				"\t%s\t%s%s\t`json:\"%s\" bson:\"%s\"`\n",
				ez.Ucfirst(field.GetName()),
				field.GetType(),
				field.GetSrc(),
				field.GetName(),
				field.GetName(),
			)
		}
		content += "}\n"
	}
	return content
}

func CreateCrud(creator *Creator) {
	content := twigger.Render("/mongodb/model_func.twig", creator)
	createCrudFile(creator, []byte(content))
}
